<template>
    <div>
        <p>购物车列表</p>
        <table  >
            <tr >
                <td>序号</td>
                <td>名称</td>
                <td>数量</td>
                <td>价格</td>

            </tr>
            <tr v-for="(c,index) in cart" :class="{active:c.active}" :key="c.id">
                <td><input type="checkbox" v-model="c.active"></td>
                <td>{{c.text}}</td>
                <td><button @click="miscount(index)">-</button>{{c.count}}<button @click="addcount(index)">+</button></td>
                <td>￥{{c.price * c.count}}</td>
            </tr>
            <tr border="1">
                <td></td>
                <td colspan="2">商品数量：{{activeCount}}/{{count}}</td>
                <td>总价钱：{{total}}</td>
            </tr>
        </table>
    </div>
</template>

<script>
    export default {
        name: "",
        data(){
            return {
                cart: JSON.parse(localStorage.getItem("cart")) || [],
            }
        },
        computed:{
            activeCount:function () {
               return  this.cart.filter(c => c.active).length
            },
            count:function(){
                return this.cart.length;
            },
            total:function(){
                let num = 0;
                this.cart.forEach(c => {
                    num = num + c.price * c.count;
                })
                return num;
            }
        },
        methods:{
            miscount(index){
                if(this.cart[index].count > 1){
                    this.cart[index].count -= 1;
                }else{
                    this.remove(index)
                }
            },
            addcount(index){
                this.cart[index].count += 1;
            },
            remove(index){
                if(window.confirm("确定要删除吗？")){
                    this.cart.splice(index,1);
                }
            },
        },
        created(){
            this.$bus.$on("addCart",good=>{
                const ret = this.cart.find(v => v.id === good.id);
                if(ret){
                    ret.count +=1
                }else{
                    this.cart.push({
                            ...good,
                            count: 1,
                            active: true
                        }
                    );
                }
            })
        },
        watch:{
            cart:{
                handler(n,o){
                    localStorage.setItem("cart",JSON.stringify(n));
                },
                deep: true
            }
        }
    }
</script>

<style scoped>
    table,th,td{
        border: 1px solid #eeeeee;
    }
    .active{
        color:#00B7FF;
    }

</style>